#include "storage.h"
#include <QFile>
#include <QByteArray>
#include <QDebug>
#include <string.h>
using std::string;


Storage::Storage()
{
}

QVector<Person> Storage::load(QString fileName) {
    QVector<Person> people;
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        qDebug() << "error";

    while (!file.atEnd()) {
        Person person;
        QByteArray tmp = file.readLine();
        person.name = tmp;
        tmp = file.readLine();
        person.lastname = tmp;
        tmp = file.readLine();
        person.phone = tmp;
        tmp = file.readLine();
        person.email = tmp;
        tmp = file.readLine();
        person.notes = tmp;
        people.append(person);
    }
    file.close();
    return people;
}

void Storage::save(QVector<Person> const & people, const QString filename) {
    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        qDebug() << "error";
    for (int i = 0; i != people.size(); ++i) {
        writeStringToFile(file, people.at(i).name);
        writeStringToFile(file, people.at(i).lastname);
        writeStringToFile(file, people.at(i).phone);
        writeStringToFile(file, people.at(i).email);
        writeStringToFile(file, people.at(i).notes);
//        file.write(people.at(i).lastname.toStdString().c_str());
//        file.write(people.at(i).phone.toStdString().c_str());
//        file.write(people.at(i).email.toStdString().c_str());
//        file.write(people.at(i).notes.toStdString().c_str());
    }
    file.close();
}

void Storage::writeStringToFile(QFile & file, QString const & qstring) {
    string tmp = qstring.toStdString();
    if (tmp[0] == '\n') {
        tmp = tmp.substr(1);
    }
    file.write(tmp.c_str());
    if ((tmp[tmp.size()-1]) != '\n') {
        file.write("\n");
    }
}
